﻿<!DOCTYPE HTML>
<html lang="zh">
<head>
<title>RegExMatch - 语法 &amp; 使用 | AutoHotkey v2</title>
<meta name="description" content="The RegExMatch function determines whether a string contains a pattern (regular expression)." />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="../static/theme.css" rel="stylesheet" type="text/css" />
<script src="../static/content.js" type="text/javascript"></script>
<script type="text/javascript">$(function(){0<=window.navigator.userAgent.toLowerCase().indexOf("ucbrowser")&&CaoNiMaDeUc()})</script>
</head>
<body>

<h1>RegExMatch</h1>

<p>Determines whether a string contains a pattern (regular expression).</p>

<pre class="Syntax">FoundPos := <span class="func">RegExMatch</span>(Haystack, NeedleRegEx <span class="optional">, OutputVar, StartingPosition := 1</span>)</pre>
<h2 id="Parameters">参数</h2>
<dl>

  <dt>Haystack</dt>
  <dd>
    <p>类型: <a href="../Concepts.htm#strings">字符串</a></p>
    <p>The string whose content is searched. This may contain binary zero.</p>
  </dd>

  <dt>NeedleRegEx</dt>
  <dd>
    <p>类型: <a href="../Concepts.htm#strings">字符串</a></p>
    <p>The pattern to search for, which is a Perl-compatible regular expression (PCRE). The pattern's <a href="../misc/RegEx-QuickRef.htm#Options">options</a> (if any) must be included at the beginning of the string followed by a close-parenthesis. 例如, the pattern &quot;<span class="red">i)</span>abc.*123&quot; would turn on the case-insensitive option and search for &quot;abc&quot;, followed by zero or more occurrences of any character, followed by &quot;123&quot;. If there are no options, the &quot;)&quot; is optional; 例如, &quot;)abc&quot; is equivalent to &quot;abc&quot;.</p>
    <p>Although <em>NeedleRegEx</em> cannot contain binary zero, the pattern <code>\x00</code> can be used to match a binary zero within <em>Haystack</em>.</p>
  </dd>

  <dt>OutputVar</dt>
  <dd>
    <p>类型: <a href="../Concepts.htm#variables">变量</a></p>
    <p>Specify a variable in which to store a <a href="#MatchObject">match object</a>, which can be used to retrieve the position, length and value of the overall match and of each <a href="../misc/RegEx-QuickRef.htm#subpat">captured subpattern</a>, if any are present.</p>
    <p>If the pattern is not found (that is, if the function returns 0), this variable is made blank.</p>
  </dd>

  <dt>StartingPosition</dt>
  <dd>
    <p>类型: <a href="../Concepts.htm#numbers">整数</a></p>
    <p>If <em>StartingPosition</em> is omitted, it defaults to 1 (the beginning of <em>Haystack</em>). Otherwise, specify 2 to start at the second character, 3 to start at the third, and so on. If <em>StartingPosition</em> is beyond the length of <em>Haystack</em>, the search starts at the empty string that lies at the end of <em>Haystack</em> (which typically results in no match).</p>
    <p>Specify a negative <em>StartingPosition</em> to start at that position from the right. 例如, -1 starts at the last character and -2 starts at the next-to-last character. If <em>StartingPosition</em> tries to go beyond the left end of <em>Haystack</em>, all of <em>Haystack</em> is searched.</p>
    <p>Regardless of the value of <em>StartingPosition</em>, the return value is always relative to the first character of <em>Haystack</em>. 例如, the position of &quot;abc&quot; in &quot;123abc789&quot; is always 4.</p>
  </dd>

</dl>

<h2 id="Return_Value">返回值</h2>
<p>类型: <a href="../Concepts.htm#numbers">整数</a></p>
<p>This function returns the position of the leftmost occurrence of <em>NeedleRegEx</em> in the string <em>Haystack</em>. Position 1 is the first character. Zero is returned if the pattern is not found.</p>

<h2 id="Errors">错误</h2>
<p><strong>Syntax errors:</strong> If the pattern contains a syntax error, an <a href="Throw.htm#Exception">exception</a> is thrown with a message in the following form: <em>Compile error N at offset M: description</em>. In that string, <em>N</em> is the PCRE error number, <em>M</em> is the position of the offending character inside the regular expression, and <em>description</em> is the text describing the error.</p>
<p><strong>Execution errors:</strong> If an error occurs during the <em>execution</em> of the regular expression, an <a href="Throw.htm#Exception">exception</a> is thrown. The <em>Extra</em> property of the exception object contains the PCRE error number. Although such errors are rare, the ones most likely to occur are &quot;too many possible empty-string matches&quot; (-22), &quot;recursion too deep&quot; (-21), and &quot;reached match limit&quot; (-8). If these happen, try to redesign the pattern to be more restrictive, such as replacing each * with a ?, +, or a limit like {0,3} wherever feasible.</p>

<h2>Options</h2>
<p>See <a href="../misc/RegEx-QuickRef.htm#Options">Options</a> for modifiers such as &quot;<span class="red">i)</span>abc&quot;, which turns off case-sensitivity in the pattern &quot;abc&quot;.</p>

<h2 id="MatchObject">Match Object</h2>
<p>If a match is found, an object containing information about the match is stored in <em>OutputVar</em>. This object has the following 属性:</p>
<p><strong>Match.Pos(N)</strong>: Returns the position of the overall match or a captured subpattern.</p>
<p><strong>Match.Len(N)</strong>: Returns the length of the overall match or a captured subpattern.</p>
<p><strong>Match.Value(N)</strong>: Returns the overall match or a captured subpattern.</p>
<p><strong>Match.Name(N)</strong>: Returns the name of the given subpattern, if it has one.</p>
<p><strong>Match.Count()</strong>: Returns the overall number of subpatterns.</p>
<p><strong>Match.Mark()</strong>: Returns the <em>NAME</em> of the last encountered <code>(*MARK:NAME)</code>, when applicable.</p>
<p><strong>Match[N]</strong>: If <em>N</em> is 0 or a valid subpattern number or name, this is equivalent to <code>Match.Value(N)</code>.</p>
<p><strong>Match.N</strong>: Same as above, except that <em>N</em> is an unquoted name or number.</p>
<p>For all of the above properties, <em>N</em> can be any of the following:</p>
<ul>
  <li>0 for the overall match.</li>
  <li>The number of a subpattern, even one that also has a name.</li>
  <li>The name of a subpattern.</li>
</ul>
<p>The object also supports enumeration; that is, the <a href="For.htm">for-loop</a> is supported. Alternatively, use <code><a href="Loop.htm">Loop</a> Match.Count()</code>.</p>

<h2>Performance</h2>
<p>To search for a simple substring inside a larger string, use <a href="InStr.htm">InStr</a> because it is faster than RegExMatch.</p>
<p>To improve performance, the 100 most recently used regular expressions are kept cached in memory (in compiled form).</p>
<p>The <a href="../misc/RegEx-QuickRef.htm#Study">study option (S)</a> can sometimes improve the performance of a regular expression that is used many times (such as in a loop).</p>

<h2 id="Remarks">备注</h2>
<p id="NamedSubPat">A subpattern may be given a name such as the word <em>Year</em> in the pattern &quot;(?P&lt;Year&gt;\d{4})&quot;. Such names may consist of up to 32 alphanumeric characters and underscores. Note that named subpatterns are also numbered, so if an <a href="../misc/RegEx-QuickRef.htm#subpat">unnamed subpattern</a> occurs after &quot;Year&quot;, it would be stored in <code>OutputVar[2]</code>, not <code>OutputVar[1]</code>.</p>
<p>Most characters like abc123 can be used literally inside a regular expression. However, the characters <strong>\.*?+[{|()^$</strong> must be preceded by a backslash to be seen as literal. 例如, <strong>\.</strong> is a literal period and <strong>\\</strong> is a literal backslash. Escaping can be avoided by using \Q...\E. 例如: <code>\QLiteral Text\E</code>.</p>
<p>Within a regular expression, special characters such as tab and newline can be escaped with either an accent (`) or a backslash (\). 例如, `t is the same as \t except when the <b>x</b> option is used.</p>
<p>To learn the basics of regular expressions (or refresh your memory of pattern syntax), 请参阅 the <a href="../misc/RegEx-QuickRef.htm">RegEx Quick Reference</a>.</p>
<p>AutoHotkey's regular expressions are implemented using Perl-compatible Regular Expressions (PCRE) from <a href="http://www.pcre.org/">www.pcre.org</a>.</p>
<p>Within an <a href="../Variables.htm#Expressions">expression</a>, the <code>a <a href="../Variables.htm#regex">~=</a> b</code> can be used as shorthand for <code>RegExMatch(a, b)</code>.</p>
<h2 id="Related">相关</h2>
<p><a href="RegExReplace.htm">RegExReplace</a>, <a href="../misc/RegEx-QuickRef.htm">RegEx Quick Reference</a>, <a href="../misc/RegExCallout.htm">Regular Expression Callouts</a>, <a href="InStr.htm">InStr</a>, <a href="SubStr.htm">SubStr</a>, <a href="SetTitleMatchMode.htm#RegEx">SetTitleMatchMode RegEx</a>, <a href="https://www.autohotkey.com/forum/topic16164.html">Global matching and Grep (forum link)</a></p>
<p>Common sources of text data: <a href="FileRead.htm">FileRead</a>, <a href="Download.htm">Download</a>, <a href="../misc/A_Clipboard.htm">A_Clipboard</a>, <a href="GuiControls.htm#Edit">GUI Edit controls</a></p>

<h2 id="Examples">示例</h2>
<p>For general RegEx examples, see the <a href="../misc/RegEx-QuickRef.htm">RegEx Quick Reference</a>.</p>

<div class="ex" id="ExBasic">
<p><a href="#ExBasic">#1</a></p>
<pre>MsgBox RegExMatch(&quot;xxxabc123xyz&quot;, &quot;abc.*xyz&quot;)  <em>; Shows 4, which is the position where the match was found.</em>
MsgBox RegExMatch(&quot;abc123123&quot;, &quot;123$&quot;)  <em>; Shows 7 because the $ requires the match to be at the end.</em>
MsgBox RegExMatch(&quot;abc123&quot;, &quot;i)^ABC&quot;)  <em>; Shows 1 because a match was achieved via the case-insensitive option.</em>
MsgBox RegExMatch(&quot;abcXYZ123&quot;, &quot;abc(.*)123&quot;, SubPat)  <em>; Shows 1 and stores &quot;XYZ&quot; in SubPat[1].</em>
MsgBox RegExMatch(&quot;abc123abc456&quot;, &quot;abc\d+&quot;, &quot;&quot;, 2)  <em>; Shows 7 instead of 1 due to StartingPosition 2 vs. 1.</em></pre>
</div>

<div class="ex" id="ExObject">
<p><a href="#ExObject">#2</a>: Match object</p>
<pre>FoundPos := RegExMatch(&quot;Michiganroad 72&quot;, &quot;(.*) (?&lt;nr&gt;\d+)&quot;, SubPat)
MsgBox SubPat.Count() ": " SubPat.Value(1) " " SubPat.Name(2) "=" SubPat["nr"]  <em>; Displays "2: Michiganroad nr=72"</em></pre>
</div>

<div class="ex" id="ExExtension">
<p><a href="#ExExtension">#3</a>: A simple example which retrieves the extension of a file. Note that <a href="SplitPath.htm">SplitPath</a> can also be used for this, which is more reliable.</p>
<pre>Path := "C:\Foo\Bar\Baz.txt"
RegExMatch(Path, "\w+$", Extension)
MsgBox Extension[0]  <em>; Shows "txt".</em></pre>
</div>

</body>
</html>